#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>

#define BUF_LEN 40

int main()
{
    char write_buf[BUF_LEN]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
    char read_buf[BUF_LEN]={0};
    int fd;
    int code,i;

    fd = open("/dev/scull0",O_WRONLY );
    if (fd < 0) {
        perror("open failed");
        exit(1);
    }

    for (i=0; i<BUF_LEN; i++) {
        write_buf[i] = '0' + i;
    }

    for (i=BUF_LEN ; i>0 ; i-=code)		{  
        code=write(fd , &write_buf[BUF_LEN-i] , i);
        if (code < 0) {
            perror("write error");
            exit(1);
        } else if (code != i) {
            printf("write part! code=%d \n",code);
        } else {
            printf("write full! code=%d \n",code);
        }
    }

    close(fd);

    fd = open("/dev/scull0",O_RDONLY );
    if (fd < 0) {
        perror("open failed");
        exit(1);
    }

    for ( i=BUF_LEN ; i>0 ; i-=code)		{  
        code=read(fd , &read_buf[BUF_LEN-i] , i);
        if (code < 0) {
            perror("read error");
            exit(1);
        } else if (code != i) {
            printf("read part! code=%d \n",code);
        } else {
            printf("read full! code=%d \n",code);
        }
    }

    close(fd);

    for(i=0;i<BUF_LEN;i+=5) 
        printf("[%d]=%d [%d]=%d [%d]=%d [%d]=%d [%d]=%d\n",
                i,read_buf[i],i+1,read_buf[i+1],i+2,read_buf[i+2],i+3,read_buf[i+3],i+4,read_buf[i+4]);

    printf("\n"); 

    exit(0);
}
